package com.xpgk.xpsoft.code;

import java.util.List;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.xpgk.common.kit.CacheKitEx;
import com.xpgk.common.kit.PubKit;
import com.xpgk.xpsoft.common.XPSoftService;
import com.xpgk.xpsoft.constants.XPSoftConstant;

public class CodeService extends XPSoftService {

	// 得到代码列表
	static public List<Record> getCodeList(Integer systemID, String type) {
		List<Record> list = CacheKitEx.get(XPSoftConstant.cacheName, XPSoftConstant.cacheKey_CodeList(systemID, type));
		if (list == null) {
			list = Db.find(Db.getSql("xpSoftCode.findCodesList"), systemID, type);
			CacheKitEx.put(XPSoftConstant.cacheName, XPSoftConstant.cacheKey_CodeList(systemID, type), list);
		}
		return list;
	}

	static public List<Record> getCodeList(String type) {
		return getCodeList(XPSoftConstant.systemID, type);
	}

	// 得到行政区化列表
	static public List<Record> getXZQHList() {
		return getCodeList(0, "1");
	}

	static public synchronized String saveCode(Record code) {
		Integer value = code.getInt("systemID");
		if (value == null)
			code.set("systemID", XPSoftConstant.systemID);

		code.remove("id");
		if (ExistCodeType(code.getInt("systemID"), code.getStr("type"), code.getStr("dmz")) != null) {
			return "dmz had exist";
		}
		;
		Db.save("frm_code", code);
		CacheKitEx.remove(XPSoftConstant.cacheName,
				XPSoftConstant.cacheKey_CodeList(code.getInt("systemID"), code.getStr("type")));
		return "ok";
	}

	// 添加用户
	static public Integer ExistCodeType(Integer systemID, String type, String dmz) {
		return Db.queryInt("select id from frm_code where systemID=? and type=? and dmz=?", systemID, type, dmz);
	}

	static public String updateCode(Record code) {
		if (code == null || code.get("id") == null)
			return "错误信息。";
		Integer id = ExistCodeType(code.getInt("systemID"), code.getStr("type"), code.getStr("dmz"));
		if (id != null && id != PubKit.toInt(code.get("id"))) {
			return "dmz had exist";
		}
		;
		if (Db.update("frm_code", code)) {
			CacheKitEx.remove(XPSoftConstant.cacheName,
					XPSoftConstant.cacheKey_CodeList(code.getInt("systemID"), code.getStr("type")));
			return "ok";
		}
		return "错误信息。";
	}
}
